<template>
   <div class="app-container">
     <!-- 搜索区 -->
     <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
       <el-form-item label="字典名称" prop="dictName">
         <el-input v-model="queryParams.dictName" placeholder="请输入字典名称" clearable style="width: 240px"
           @keyup.enter.native="handleQuery" />
       </el-form-item>

       <el-form-item label="字典类型" prop="dictType">
         <el-input v-model="queryParams.dictType" placeholder="请输入字典类型" clearable style="width: 240px"
           @keyup.enter.native="handleQuery" />
       </el-form-item>

       <el-form-item label="字典状态" prop="status">
         <el-select v-model="queryParams.status" placeholder="请选择" clearable>
             <el-option
               v-for="item in dicts.sys_normal_disable"
               :key="item.id"
               :label="item.dictLabel"
               :value="item.dictValue">
             </el-option>
           </el-select>
      </el-form-item>

     <el-form-item label="创建时间"  >
          <el-date-picker
               v-model="createTimeValue"
               type="daterange"
               value-format="yyyy-MM-dd"
               range-separator="至"
               start-placeholder="开始日期"
               end-placeholder="结束日期">
             </el-date-picker>
     </el-form-item>

       <el-form-item>
         <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
       </el-form-item>
     </el-form>

     <!-- 功能区 -->
     <el-row>
       <el-col :span="24">
          <el-button type="primary" size="small"  @click="handlerAdd()" >新增</el-button>
          <el-button type="warning" size="small"  @click="handlerUpdate()" :disabled="single" >修改</el-button>
          <el-button type="success" size="small"  @click="handlerExcel()"  >导出</el-button>
       </el-col>
     </el-row>

     <el-table :data="tableData.rows" border style="width: 100%"  v-loading="loading" @selection-change="handleSelectionChange">
       <el-table-column type="selection" width="55" align="center"  />
       <el-table-column prop="id" label="编号" width="80" />
       <el-table-column prop="dictName" label="字典名称"  />
       <el-table-column prop="dictType" label="字典类型">
         <template slot-scope="scope">
            <!-- <router-link :to="`/dict-data/${scope.row.id}`">{{scope.row.dictType}}</router-link> -->
           <router-link :to="'/dict-data/'+scope.row.id" class="link-type">{{scope.row.dictType}}</router-link>
         </template>
       </el-table-column>

       <el-table-column label="状态" width="180">
         <template slot-scope="scope">
           <el-tag  v-for="item in dicts.sys_normal_disable" :key="item.id" v-if="item.dictValue=== scope.row.status" :type="item.listClass" >{{item.dictLabel}}</el-tag>
         </template>
       </el-table-column>

       <el-table-column prop="remark" label="备注"  />

       <el-table-column prop="createTime" label="创建时间" width="180" />

       <el-table-column label="操作" align="left" width="160" class-name="small-padding fixed-width">
         <template slot-scope="scope">
           <el-button   size="mini" type="text" icon="el-icon-edit" @click="handlerUpdate(scope.row)">修改</el-button>
           <el-button v-if="scope.row.status==='0'" size="mini"  type="text" icon="el-icon-delete" style="color:red;" @click="handlerDisable(scope.row)">停用</el-button>
           <el-button v-else-if="scope.row.status==='1'" size="mini" type="text" icon="el-icon-video-play" @click="handlerEnable(scope.row)">启用</el-button>
         </template>
       </el-table-column>
     </el-table>

     <!-- 分页条 -->
     <el-pagination v-if="tableData.total>0" :current-page="queryParams.page" :page-sizes="[1, 5, 10, 20,30,50,100]"
       :page-size="queryParams.size" layout="total, sizes, prev, pager, next, jumper" :total="tableData.total"
       @size-change="handleSizeChange" @current-change="handleCurrentChange" />

     <!-- 新增和修改的对话框 -->
     <el-dialog 	v-bind:title="title"  :visible.sync="dialogVisible"  width="500px"  :close-on-click-modal="false"   >
       <!-- 内容 -->
     				<el-form ref="form" :model="form" label-width="80px">

              <el-form-item  v-if="form.id"  label="字典类型"  >
                <b>{{form.dictType}}</b>
              </el-form-item>
              <el-form-item v-else  label="字典类型" prop="dictType" :rules="[{ required: true, message: '不能为空', trigger: 'blur' } ]"  >
                <el-input v-model="form.dictType"></el-input>
              </el-form-item>


               <el-form-item   label="字典名称" prop="dictName" :rules="[{ required: true, message: '不能为空', trigger: 'blur' } ]">
                 <el-input v-model="form.dictName"></el-input>
               </el-form-item>


               <el-form-item label="状态"  >
                 <el-radio-group v-model="form.status">
                     <el-radio v-for="item in dicts.sys_normal_disable" :key="item.id" :label="item.dictValue">{{item.dictLabel}}</el-radio>
                 </el-radio-group>
               </el-form-item>

               <el-form-item label="备注"  >
                 <el-input  type="textarea" :rows="2"  placeholder="请输入内容"  v-model="form.remark">
                 </el-input>
               </el-form-item>
     				</el-form>

         <span slot="footer" class="dialog-footer">
           <el-button @click="resetForm">取 消</el-button>
           <el-button type="primary" @click="saveFormBefore">确 定</el-button>
         </span>
     </el-dialog>


    </div>
</template>

<script>
   import {dataApi,findByIdApi,addApi,updateApi,changeStatusApi} from '@/api/dicttype.js'
   import {dataDictTypes } from '@/api/dictdata.js'

  export default {
    data() {
      return {
        createTimeValue: [],
        loading: false,
        // 表单查询条件对象
        queryParams:{
          page: 1,
          size: 10
        },
        // 分页表格分页的结果对象
         tableData: {
           total: 0,
           rows: []
         },
         //表格选中的对象
         mutilrows:[],
         //表格选中对象的主键的值
         ids: [],
         //编辑按钮禁用
         single: true,
         //数据字典返回结果
         dicts: {},
         //对话框的变量
         title: '添加数据',
         dialogVisible: false,
         form: {
           status: '0'
         },
      }
    },
    methods: {
      handlerAdd(){
        //显示对话框
         this.dialogVisible =true
         this.title='添加数据'
      },
      handlerUpdate(row){
        let id;
         if(row){
           id=row.id
         }else{
           id=this.ids[0]
         }
         //根据主键查询数据，回填充form表单中
         findByIdApi(id).then(resp=> {
           this.form = resp.data

           this.dialogVisible =true
           this.title='编辑数据'
         })
      },
      handlerExcel(){
        if(this.ids && this.ids.length>0){
          this.download('/api/dicttype/download/choice', {'ids':this.ids},`数据字典列表_${new Date().getTime()}.xlsx`)
        }else{
          this.download('/api/dicttype/download', this.queryParams,`数据字典列表_${new Date().getTime()}.xlsx`)
        }
      },
     //选中表格值的变化事件
      handleSelectionChange(val) {
        console.log(val)
          this.mutilrows = val;
          // this.ids= val.map(function(s){
          //   return  s.id
          // } );
          this.ids=val.map(s=> s.id);
          this.single = val.length!==1
      },
     // 每页几笔发生变化
      handleSizeChange(val) {
         this.queryParams.page=1
         this.queryParams.size=val
         // 重新查询
         this.fetchData()
     },
     // 当前页发生变化
     handleCurrentChange(val) {
         this.queryParams.page=val
          // 重新查询
          this.fetchData()
     },
     // 获取后台的查询数据
     fetchData(){
       this.loading=true
       dataApi(this.queryParams).then(resp=> {
           this.tableData.total = resp.data.total
           this.tableData.rows = resp.data.list
           this.loading =false
       })
     },
     //点击搜索按钮
     handleQuery(){
       this.queryParams.page =1
       this.fetchData()
     },
     //查询数据字典的值
     fetchDictTypes() {
       const params= ['sys_normal_disable']
       dataDictTypes(params).then(resp=> {
          this.dicts = resp.data
       })
     },
     //重置表单
     resetForm(){
        //清空验证规则样式
        this.$refs['form'].resetFields();
        //清除数据
        this.form={
          status: '0'
        }
        //关闭对话框
        this.dialogVisible =false
     },
     //提交保存数据之前验证
     saveFormBefore(){
        //验证数据是否都有效了
         this.$refs['form'].validate((valid) => {
          if (valid) {
             //验证成功
             this.$confirm('确定要保存数据吗?', '提示', {
                       confirmButtonText: '确定',
                       cancelButtonText: '取消',
                       type: 'warning'
                     }).then(() => {
                        //提交
                         this.saveForm();

                     }).catch(() => {
                       //不提交操作
                     });

          } else {
            return false;
          }
        });
     },
     //向后台提交数据
      saveForm(){
        //修改
        let saveApi;
        if(this.form.id){
           saveApi= updateApi;
        }else{
           saveApi =addApi
        }

        saveApi(this.form).then(resp=> {
            this.$message({message: '操作成功', type: 'success'});
            //关闭窗体
            this.resetForm()
            //重新查询数据
            this.fetchData()
        })

      },
      //停用账户
      handlerDisable(row){
        this.confirmTips('确定要停用该数据吗？',()=>{
          this.changeStates(row.id,'1')
        })
      },
      //启用账户
      handlerEnable(row){
        this.confirmTips('确定要启用该数据吗？',()=> {
          this.changeStates(row.id,'0')
        })
      },
      //更改账号状态
      changeStates(id,status){
         changeStatusApi( {'id': id, 'status': status}).then(resp=> {
           this.$message({message: '操作成功', type: 'success'});
           //重新查询数据
           this.fetchData()
         })
      },
    },
    created() {
      this.fetchDictTypes()
      this.fetchData()
    }
  }
</script>

<style scoped>
  .link-type, .link-type:focus {
      color: #337ab7;
      cursor: pointer;
  }
</style>
